<template>
    <div class="login-wrap"
         style="background-image: url('https://jingo-1254525529.cos.ap-shanghai.myqcloud.com/img/back-bing.jpg')">
        <div class="ms-title">INYU内容管理平台</div>
        <div class="ms-login" style="opacity: 0.9">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
                <el-form-item prop="username">
                    <el-input v-model="ruleForm.username"
                              placeholder="username">
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password"
                              placeholder="password"
                              v-model="ruleForm.password"
                              @keyup.enter.native="submitForm('ruleForm')">

                    </el-input>
                </el-form-item>

                <el-form-item prop="captcha">
                    <div id="captcha">
                        <div id="wait" class="show">
                            正在加载验证码......
                        </div>
                    </div>
                </el-form-item>

                <el-form-item style="width:100%;     margin-bottom: 10px">
                    <el-button type="primary" style="width:45%; "
                               id="btn"
                               @click.native.prevent="handleSubmit"
                               :loading="logining">
                        登录
                    </el-button>
                    <el-button style="width:45%;"
                               @click.native.prevent="handleReset">
                        注册
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="footer-copy"> ©&nbsp;2019-2020&nbsp;&nbsp;&nbsp; mount.pub All Right Reserved ·&nbsp;<a
            href="http://beian.miit.gov.cn" rel="link" target="_blank">浙ICP备19049913号-1</a> ·&nbsp;<b
            style="color: #ff4425;">♥</b>&nbsp;Owner By <a href="https://www.mount.pub" title="mount" rel="link"
                                                           target="_blank">mount.pub</a>
        </div>
    </div>
</template>
<script>
    import { geeTestRegister, geeTestValidate} from '../api/system/geeTest';
    import {requestLogin } from '../api/system/user';
    import gt from "../assets/geetest/gt";
    import $ from 'jquery'

    export default {
        data: function () {
            return {
                logining: false,
                ruleForm: {
                    username: '',
                    password: '',
                    captcha: ''
                },
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                    ]
                },
                checked: true,
                msg: '',
                gtValidate: {},
                gtValRet: false,
            }
        },
        methods: {
            handleReset() {
                this.$refs.ruleForm.resetFields();
            },
            getBackgroupPic() {
                getBingPic(null).then(res => {
                    this.logining = false;
                    if (!res.status) {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    } else {
                        sessionStorage.setItem('user', JSON.stringify(res.data));
                        this.$router.push({path: '/table'});
                    }
                });
            },
            geeTestInit() {
                let params = {'t': (new Date()).getTime()};
                geeTestRegister(params).then(data => {
                    let that = this;
                    if (data.success) {
                        // 调用 initGeetest 进行初始化
                        // 参数1：配置参数
                        // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口
                        initGeetest({
                            // 以下 4 个配置参数为必须，不能缺少
                            gt: data.gt,
                            challenge: data.challenge,
                            // 表示用户后台检测极验服务器是否宕机
                            offline: !data.success,
                            // 用于宕机时表示是新验证码的宕机
                            new_captcha: data.new_captcha,
                            // 产品形式，包括：float，popup
                            product: "float",
                            width: "300px"
                            // 更多配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
                        }, (captchaObj) => {
                            captchaObj.onReady(function () {
                                $("#wait").hide();
                            });
                            // 将验证码放在宿主页面，呼应【步骤3】
                            captchaObj.appendTo("#captcha");
                            // 这里调用了 onSuccess 方法，该方法介绍见下文
                            captchaObj.onSuccess(() => {
                                var result = captchaObj.getValidate();
                                this.gtValidate = result
                                let datas = {
                                    geetest_challenge: result.geetest_challenge,
                                    geetest_validate: result.geetest_validate,
                                    geetest_seccode: result.geetest_seccode
                                };
                                geeTestValidate(datas).then(res => {
                                    if (res.status === 'success') {
                                        that.gtValRet = true;
                                    } else if (res.status === 'fail') {
                                        that.gtValRet = false;
                                        captchaObj.reset();
                                        this.$message({
                                            message: "【极验】校验失败!",
                                            type: 'error'
                                        });
                                    }
                                });
                            });
                        });
                    } else {
                        console.error("geeTest初始化失败，请联系管理员！")
                    }
                });
            },

            handleSubmit() {
                let ret = this.gtValRet;
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        if (!ret) {
                            this.$message({
                                message: "请完成验证!",
                                type: 'error',
                                duration: 2
                            });
                            return;
                        }
                        this.logining = true;

                        let para = Object.assign({}, this.ruleForm);
                        requestLogin(para).then(res => {
                            if (!res.status) {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                                this.logining = false;
                            } else {
                                localStorage.setItem('ms_username', res.data.user.nickname);
                                localStorage.setItem('ms_avatar', res.data.user.avatar);
                                localStorage.setItem('user', JSON.stringify(res.data.user));
                                sessionStorage.setItem('token', res.data.token);
                                // sessionStorage.setItem('uid', JSON.stringify(res.data.user.id));
                                this.$router.push('/');
                            }
                        });
                    } else {
                        return false;
                    }
                });
            }
        }, mounted() {
            this.geeTestInit();
        }
    }
</script>


<style scoped>
    .login-wrap {
        position: relative;
        width: 100%;
        height: 100%;
    }

    .ms-title {
        position: absolute;
        top: 50%;
        width: 100%;
        margin-top: -230px;
        text-align: center;
        font-size: 30px;
        color: #fff;

    }

    .ms-login {
        position: absolute;
        left: 50%;
        top: 50%;
        width: 300px;
        height: 190px;
        margin: -150px 0 0 -190px;
        padding: 40px;
        border-radius: 5px;
        background: #fff;
    }

    .login-btn {
        text-align: center;
    }

    .login-btn button {
        width: 100%;
        height: 36px;
    }

    .footer-copy {
        font-size: 6px;
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #c0c4cc;
    }

    a:link {
        color: #bf9191;
    }
</style>
